package com.cxq.boot.advice;

import com.alibaba.fastjson.JSON;
import com.cxq.boot.dto.ResultDTO;
import com.cxq.boot.exception.CustomizeErrorCode;
import com.cxq.boot.exception.CustomizeException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//处理通用异常（springmvc给handler的异常）
@ControllerAdvice
public class CustomizeExceptionHandler {
    @ExceptionHandler(Exception.class)
    //不是同时放回json或页面
    //@ResponseBody
    public ModelAndView handle(HttpServletRequest request, Throwable ex, Model model,
                               HttpServletResponse response) {
        //status没有使用，可以去掉
        //HttpStatus status = getStatus(request);
        String contentType = request.getContentType();
        if ("application/json".equals(contentType)){
            ResultDTO resultDTO;
            //返回JSO你
            if (ex instanceof CustomizeException) {
                //model.addAttribute("message", ex.getMessage());
                resultDTO = ResultDTO.errorOf((CustomizeException)ex);
            } else {
                //model.addAttribute("message", "服务器出差去了，请稍后来访问哦");
                resultDTO = ResultDTO.errorOf(CustomizeErrorCode.SYS_ERROR);
            }
            try {
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                //使用这种方式放回JSON
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(resultDTO));//转成JSON写出
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;//无页面跳转
        }else {
            //返回错误页面
            if (ex instanceof CustomizeException) {
                model.addAttribute("message", ex.getMessage());
            } else {
                model.addAttribute("message", CustomizeErrorCode.SYS_ERROR.getMessage());
            }
            return new ModelAndView("error");
        }
    }

    /*private HttpStatus getStatus(HttpServletRequest request) {
        Integer code = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        //此处code为null时，可能直接抛异常了
        //HttpStatus status = HttpStatus.resolve(code);
        //return (status != null) ? status : HttpStatus.INTERNAL_SERVER_ERROR;
        if (code == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(code);
    }*/
}
